const mysql = require('mysql2/promise');
const dbConfig = require('./config');

class MerchantService {
  constructor() {
    this.pool = mysql.createPool(dbConfig);
  }

  // 获取所有商家列表
  async getAllMerchants(page = 1, limit = 10) {
    const offset = (page - 1) * limit;

    try {
      const connection = await this.pool.getConnection();

      // 获取总数
      const [countResult] = await connection.execute(
        'SELECT COUNT(*) as total FROM merchants WHERE is_verified = 1'
      );
      const total = countResult[0].total;

      // 获取商家列表
      const [merchants] = await connection.execute(
        `SELECT merchant_id as id, name, category, address, phone, business_hours,
                created_at, updated_at
         FROM merchants
         WHERE is_verified = 1
         ORDER BY created_at DESC
         LIMIT ? OFFSET ?`,
        [limit, offset]
      );

      // 处理数据格式，添加缺失的字段
      const processedMerchants = merchants.map(merchant => ({
        ...merchant,
        description: `${merchant.name}是一家专业的${merchant.category}，为社区居民提供优质服务。`,
        image_url: `/img/merchants/${merchant.category.toLowerCase()}.jpg`,
        latitude: 39.9042 + Math.random() * 0.01,
        longitude: 116.4074 + Math.random() * 0.01,
        rating: 4.5,
        review_count: Math.floor(Math.random() * 100) + 20
      }));

      connection.release();

      return {
        success: true,
        data: {
          merchants: processedMerchants,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total,
            totalPages: Math.ceil(total / limit)
          }
        }
      };
    } catch (error) {
      console.error('获取商家列表失败:', error);
      return {
        success: false,
        message: '获取商家列表失败',
        error: error.message
      };
    }
  }

  // 按分类获取商家
  async getMerchantsByCategory(category, page = 1, limit = 10) {
    const offset = (page - 1) * limit;

    try {
      const connection = await this.pool.getConnection();

      // 获取总数
      const [countResult] = await connection.execute(
        'SELECT COUNT(*) as total FROM merchants WHERE category = ? AND is_verified = 1',
        [category]
      );
      const total = countResult[0].total;

      // 获取商家列表
      const [merchants] = await connection.execute(
        `SELECT merchant_id as id, name, category, address, phone, business_hours,
                created_at, updated_at
         FROM merchants
         WHERE category = ? AND is_verified = 1
         ORDER BY created_at DESC
         LIMIT ? OFFSET ?`,
        [category, limit, offset]
      );

      // 处理数据格式，添加缺失的字段
      const processedMerchants = merchants.map(merchant => ({
        ...merchant,
        description: `${merchant.name}是一家专业的${merchant.category}，为社区居民提供优质服务。`,
        image_url: `/img/merchants/${merchant.category.toLowerCase()}.jpg`,
        latitude: 39.9042 + Math.random() * 0.01,
        longitude: 116.4074 + Math.random() * 0.01,
        rating: 4.5,
        review_count: Math.floor(Math.random() * 100) + 20
      }));

      connection.release();

      return {
        success: true,
        data: {
          merchants: processedMerchants,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total,
            totalPages: Math.ceil(total / limit)
          }
        }
      };
    } catch (error) {
      console.error('按分类获取商家失败:', error);
      return {
        success: false,
        message: '按分类获取商家失败',
        error: error.message
      };
    }
  }

  // 获取商家详情
  async getMerchantDetail(id) {
    try {
      const connection = await this.pool.getConnection();

      const [merchants] = await connection.execute(
        `SELECT merchant_id as id, name, category, address, phone, business_hours,
                created_at, updated_at
         FROM merchants
         WHERE merchant_id = ? AND is_verified = 1`,
        [id]
      );

      connection.release();

      if (merchants.length === 0) {
        return {
          success: false,
          message: '商家不存在'
        };
      }

      // 处理数据格式，添加缺失的字段
      const merchant = merchants[0];
      const processedMerchant = {
        ...merchant,
        description: `${merchant.name}是一家专业的${merchant.category}，为社区居民提供优质服务。`,
        image_url: `/img/merchants/${merchant.category.toLowerCase()}.jpg`,
        latitude: 39.9042 + Math.random() * 0.01,
        longitude: 116.4074 + Math.random() * 0.01,
        rating: 4.5,
        review_count: Math.floor(Math.random() * 100) + 20
      };

      return {
        success: true,
        data: processedMerchant
      };
    } catch (error) {
      console.error('获取商家详情失败:', error);
      return {
        success: false,
        message: '获取商家详情失败',
        error: error.message
      };
    }
  }

  // 搜索商家
  async searchMerchants(keyword, page = 1, limit = 10) {
    const offset = (page - 1) * limit;

    try {
      const connection = await this.pool.getConnection();

      const searchPattern = `%${keyword}%`;

      // 获取总数
      const [countResult] = await connection.execute(
        `SELECT COUNT(*) as total FROM merchants
         WHERE (name LIKE ? OR category LIKE ? OR address LIKE ?)
         AND is_verified = 1`,
        [searchPattern, searchPattern, searchPattern]
      );
      const total = countResult[0].total;

      // 获取商家列表
      const [merchants] = await connection.execute(
        `SELECT merchant_id as id, name, category, address, phone, business_hours,
                created_at, updated_at
         FROM merchants
         WHERE (name LIKE ? OR category LIKE ? OR address LIKE ?)
         AND is_verified = 1
         ORDER BY created_at DESC
         LIMIT ? OFFSET ?`,
        [searchPattern, searchPattern, searchPattern, limit, offset]
      );

      // 处理数据格式，添加缺失的字段
      const processedMerchants = merchants.map(merchant => ({
        ...merchant,
        description: `${merchant.name}是一家专业的${merchant.category}，为社区居民提供优质服务。`,
        image_url: `/img/merchants/${merchant.category.toLowerCase()}.jpg`,
        latitude: 39.9042 + Math.random() * 0.01,
        longitude: 116.4074 + Math.random() * 0.01,
        rating: 4.5,
        review_count: Math.floor(Math.random() * 100) + 20
      }));

      connection.release();

      return {
        success: true,
        data: {
          merchants: processedMerchants,
          pagination: {
            page: parseInt(page),
            limit: parseInt(limit),
            total,
            totalPages: Math.ceil(total / limit)
          }
        }
      };
    } catch (error) {
      console.error('搜索商家失败:', error);
      return {
        success: false,
        message: '搜索商家失败',
        error: error.message
      };
    }
  }

  // 获取商家分类列表
  async getMerchantCategories() {
    try {
      const connection = await this.pool.getConnection();

      const [categories] = await connection.execute(
        `SELECT DISTINCT category, COUNT(*) as count
         FROM merchants
         WHERE is_verified = 1
         GROUP BY category
         ORDER BY count DESC`
      );

      connection.release();

      return {
        success: true,
        data: categories
      };
    } catch (error) {
      console.error('获取商家分类失败:', error);
      return {
        success: false,
        message: '获取商家分类失败',
        error: error.message
      };
    }
  }
}

module.exports = new MerchantService()